'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 开启军功宝箱
 * @author agl
 */

var _ = require('lodash');
var moment = require('moment');
var async = require('async');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var rewardService = require('../../../../services/rewardService');
var PlayerManager = require('../../../../libs/playerManager');
var dataApi = require('../../../../libs/dataApi');
var taskService = require('../../../../services/taskService');
var pvpConf = require('../../../../config/pvpConf.js');
var constantUtil = require('../../../../util/constantUtil.js');

module.exports = function (msg, session, next) {
    var role_id = session.uid;

    var player_manager = new PlayerManager(role_id);
    var reward_list = [];
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['pvp', 'role', 'bag', 'build', 'soldier', 'task', 'accrued', 'daily_task', 'achieve'],
                    cb
                );
            },
            function (cb) {
                var pvp_model = player_manager.pvp;
                var role_model = player_manager.role;

                // 时间判断
                var now_tm = moment().unix();
                if (pvp_model.open_honor_box_tm > now_tm) {
                    return next(null, {
                        code: Code.PVP_IN_HONOR_BOX_CD
                    });
                }

                // 星数判断
                var honor_box_need_star = constantUtil.value('honor_box_need_star');
                if (pvp_model.star_count < honor_box_need_star) {
                    return next(null, {
                        code: Code.PVP_NOT_ENOUGH_STAR
                    });
                }

                pvp_model.star_count = 0;

                // 设置开宝箱冷却时间
                var honor_box_need_time = constantUtil.value('honor_box_need_time');
                pvp_model.open_honor_box_tm = now_tm + honor_box_need_time;

                // 发放奖励
                reward_list = _getHonorBoxReward(role_model.honor);
                rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_PVP, operationType.OPR_PVP_HONOR_BOX_OPEN);

                // 开启任务统计
                taskService.addCompleteMilitaryExploit(player_manager);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: reward_list
                }
            });
        }
    );
};

var _getHonorBoxReward = function (honor) {
    // 计算区间分段(ID,制取数量)
    var honor_lvl_conf = pvpConf.getHonorLvl(honor);
    if (!honor_lvl_conf) {
        console.warn('no honor lvl conf for honor value:', honor);
        return {};
    }
    var honor_lvl = honor_lvl_conf.id;
    var i;

    // 取出相应分段奖励信息(品质物品)
    var honor_box_conf = [];
    for (i = 1; i <= honor_lvl; i++) {
        honor_box_conf = _.union(honor_box_conf, dataApi.honor_box.findById(i));
    }
    if (honor_box_conf.length < 1) {
        console.warn('empty honor_box reward info for honor lvl:', honor_lvl);
        return {};
    }

    // 取出相应分段概率数据(品质概率)
    var honor_form_conf = dataApi.honor_box_form.findById(honor_lvl);

    var reward_list = [];
    for (i = 0; i < honor_lvl_conf.num; i++) {
        reward_list.push(_getRandReward(honor_box_conf, honor_form_conf));
    }

    return reward_list;
};

var _getRandReward = function (honor_box_conf, honor_form_conf) {
    // 按概率规则计算最终奖励信息
    var quality = _randQuality(honor_form_conf);

    return _randReward(honor_box_conf, quality);
};

// 随机出品质
var _randQuality = function (honor_form_conf) {
    var prob_list = [];
    var total = 0;
    _.forEach(honor_form_conf, function (conf) {
        total += conf.probability;
        prob_list.push({
            quality: conf.quality,
            total_prob: total
        });
    });
    var rand_val = _.random(total - 1);
    return _.find(prob_list, function (item) {
        return rand_val < item.total_prob;
    }).quality;
};

// 随机出最终物品
var _randReward = function (honor_box_conf, quality) {
    var reward_list = _.filter(honor_box_conf, {
        quality: quality
    });
    if (reward_list.length < 1) {
        console.warn('invalid qualify', quality, ' for honor lvl: ', honor_box_conf[0].id);
        return {};
    }
    if (reward_list.length === 1) {
        return reward_list[0];
    }

    var reward = reward_list[_.random(reward_list.length - 1)];
    return {
        reward: reward.reward,
        reward_type: reward.reward_type,
        reward_num: reward.reward_num,
        reward_value: reward.reward_value,
        hole_num: reward.hole_num
    };
};
